import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';
import { SocialService, ITokenService, DA_SERVICE_TOKEN } from '@delon/auth';

import { IBizHttp } from './../../../ibizsys/util/IBizHttp';
import { IBizNotification } from 'app/ibizsys/util/IBizNotification';
import { IBizEnvironment } from '@env/IBizEnvironment';

@Component({
    selector: 'passport-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.less'],
    providers: [SocialService]
})
export class UserLoginComponent implements OnDestroy, OnInit {

    form: FormGroup;
    error = '';
    type = 0;
    loading = false;

    //  回调路径
    private callback: string;
    //  回调参数
    private params: any = {};

    constructor(
        fb: FormBuilder,
        private router: Router,
        private activatedRoute: ActivatedRoute,
        public msg: NzMessageService,
        private http: IBizHttp,
        private iBizNotification: IBizNotification,
        @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService) {
        this.form = fb.group({
            userName: ['ibzadmin', [Validators.required]],
            password: ['123456', Validators.required],
            mobile: [null, [Validators.required]],
            captcha: [null, [Validators.required]],
            remember: [true]
        });
    }

    // region: fields

    get userName() { return this.form.controls.userName; }
    get password() { return this.form.controls.password; }
    get mobile() { return this.form.controls.mobile; }
    get captcha() { return this.form.controls.captcha; }

    // endregion

    switch(ret: any) {
        this.type = ret.index;
    }

    // region: get captcha

    count = 0;
    interval$: any;

    getCaptcha() {
        this.count = 59;
        this.interval$ = setInterval(() => {
            this.count -= 1;
            if (this.count <= 0) {
                clearInterval(this.interval$);
            }

        }, 1000);
    }

    // endregion

    public submit(): void {
        this.error = '';
        if (this.type === 0) {
            this.userName.markAsDirty();
            this.password.markAsDirty();
            if (this.userName.invalid || this.password.invalid) {
                return;
            }
        } else {
            this.mobile.markAsDirty();
            this.captcha.markAsDirty();
            if (this.mobile.invalid || this.captcha.invalid) {
                return;
            }
        }
        // mock http
        this.loading = true;

        if (!IBizEnvironment.LocalDeve) {
            return;
        }

        let login_url: string = IBizEnvironment.RemoteLogin;
        let login_data: any = {};
        Object.assign(login_data, { username: this.userName.value, password: this.password.value });

        // 登录start
        this.http.post(login_url, login_data).subscribe(
            response => {
                if (response.ret === 0) {
                    let userData: any = {};
                    Object.assign(userData, response.data);
                    this.tokenService.set({
                        token: userData.loginkey,
                        name: userData.username,
                        email: userData.loginname,
                        id: userData.userid,
                        time: +new Date
                    });

                    let callbackstring = this.activatedRoute.snapshot.paramMap.get('callback');
                    if (!callbackstring || Object.is(callbackstring, '')) {
                        this.router.navigateByUrl('');
                    } else {
                        this.router.navigateByUrl(callbackstring);
                    }
                } else {
                    this.loading = false;
                    this.error = response.info;
                }
            },
            error => {
                this.loading = false;
                this.error = Object.is(error.info, '') ? '请求失败！' : error.info;
            }
        );
    }

    public initSystemEnv(): void {
        this.http.post(IBizEnvironment.InitSystemEnv).subscribe((result) => {
            if (result.ret === 0) {
                this.iBizNotification.info('提示', result.info);
            } else {
                this.iBizNotification.error('错误', result.info);
            }
        }, (error) => {
            this.iBizNotification.error('错误', error.info);
        })
    }

    ngOnDestroy(): void {
        if (this.interval$) {
            clearInterval(this.interval$);
        }
    }

    ngOnInit(): void {

        // 处理回调参数
        let callbackstring = this.activatedRoute.snapshot.paramMap.get('callback');
        this.callback = callbackstring == null ? '/' : callbackstring;
        let paramsdata = this.activatedRoute.snapshot.paramMap.get('params');
        let data: any = paramsdata == null ? {} : JSON.parse(paramsdata);
        Object.assign(this.params, data);
    }
}
